package com.burgeon.backend.SHOPBACKEND.service.Impl;

import com.burgeon.backend.SHOPBACKEND.entity.*;
import com.burgeon.backend.SHOPBACKEND.entity.OrderVO.OrderEntity;
import com.burgeon.backend.SHOPBACKEND.entity.OrderVO.OrderEntityItem;
import com.burgeon.backend.SHOPBACKEND.mappers.BackendOrderMapper;
import com.burgeon.backend.SHOPBACKEND.rest.*;
import com.burgeon.backend.SHOPBACKEND.rest.order.FindOrderDataDD;
import com.burgeon.backend.SHOPBACKEND.service.BackendOrderService;
import com.burgeon.backend.SHOPBACKEND.service.ex.ErrorDataException;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.service.QueueService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BackendOrderServiceImpl implements BackendOrderService {
    private final static Log logger = LogFactory.getLog(BackendOrderService.class);
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private BackendOrderMapper backendOrderMapper;
    @Autowired
    private QueueService queueService;


    //修改或新增订单备注
    private void upOrderRemark(String oid, String remark) throws ErrorDataException {
        try {
            Integer row = backendOrderMapper.upOrderRemark(oid, remark);
            if (row == 0) {
                backendOrderMapper.createOrderRemark(oid, remark);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ErrorDataException(e.getMessage());
        }
    }


    //获取订单备注
    private String getOrderRemark(String oid) {
        return backendOrderMapper.getOrderRemark(oid);
    }


    @Override
    public HashMap OrderInformation(String account) {
        //今日 昨日 7日 月
        HashMap data = new HashMap();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        Calendar x1 = Calendar.getInstance();
        x1.add(Calendar.DATE, -1);
        Date date = x1.getTime();
        int i1 = Integer.parseInt(sdf.format(date));

        Calendar x7 = Calendar.getInstance();
        x7.add(Calendar.DATE, -7);
        date = x7.getTime();
        int i7 = Integer.parseInt(sdf.format(date));

        Calendar x30 = Calendar.getInstance();
        x30.add(Calendar.DATE, -30);
        date = x30.getTime();
        int i30 = Integer.parseInt(sdf.format(date));

        double todyTot=0,yesterdayTot=0,weekTot=0,monthTot=0 ;
        int todyNum=0,yesterdayNum=0,weekNum=0,monthNum=0;


        List<OrderEntity> orderGoodsVOList = backendOrderMapper.findOrderByInformation(account);

        for (OrderEntity orderEntity : orderGoodsVOList) {
            int datei = Integer.parseInt(sdf.format(new Date()));
            int oi = timeCycle(orderEntity.getCreateTime());
            System.err.println(datei);
            System.err.println(oi);
            if (datei == oi){
                todyTot += Double.parseDouble(orderEntity.getTotPrice());
                todyNum++;
            }
            if (i1 == oi){
                yesterdayTot += Double.parseDouble(orderEntity.getTotPrice());
                yesterdayNum++;
            }

            if (i7 < oi&&datei>=oi){
                weekTot += Double.parseDouble(orderEntity.getTotPrice());
                weekNum++;
            }

            if (i30 < oi&&datei>=oi){
                monthTot += Double.parseDouble(orderEntity.getTotPrice());
                monthNum++;
            }

        }

        data.put("todyNum", todyNum);
        data.put("todyTot", todyTot);

        data.put("yesterdayNum", yesterdayNum);
        data.put("yesterdayTot", yesterdayTot);

        data.put("weekNum", weekNum);
        data.put("weekTot", weekTot);

        data.put("monthNum", monthNum);
        data.put("monthTot", monthTot);

        return data;
    }

    private int timeCycle(String time) {



        SimpleDateFormat sdfw = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdfm = new SimpleDateFormat("yyyyMMdd");


        try {
            return Integer.parseInt(sdfm.format(sdfw.parse(time)));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public void upOrderRemarkData(String oid, String remark) throws ErrorDataException {
        upOrderRemark(oid, remark);
    }

    /*
    HashMap<String,String> statemap = new HashMap<String,String>();
            statemap.put("0","未支付");
            statemap.put("1","已支付");
            statemap.put("2","已发货");
            statemap.put("3","待评论");
            statemap.put("4","已完成");
    * */
    @Override
    public OrderEntityItem findOrderItem(String id, String account) {
        System.err.println(id+","+account);
        OrderEntity orderEntity = backendOrderMapper.findOrderById(id);
        Info info = GetInfo(account);
        FindOrderDataDD findOrderDataDD = new FindOrderDataDD(info.getUrl(), info.getAccount(), info.getPassword());
        System.err.println(orderEntity.getOrderCode());
        try {
            OrderEntityItem data = findOrderDataDD.getData(orderEntity.getOrderCode());
            if (null == data) {
                return null;
            }
            data.setEndTime(orderEntity.getEndTime());
            data.setDeliverTime(orderEntity.getDeliverTime());
            data.setCreateTime(orderEntity.getCreateTime());
            data.setPayTime(orderEntity.getPayTime());
            data.setPostage(orderEntity.getMailFee());
            data.setState(orderEntity.getState());
            data.setTrackingNumber(orderEntity.getMailCode());
            data.setPayMethod("微信支付");
            data.setRemark(getOrderRemark(id));
            data.setDiscounts(String.valueOf(Double.valueOf(data.getTotPrice()) - Double.valueOf(data.getPayment())));
            data.setOrderGoodsVOS(backendOrderMapper.findOrderItemVO(orderEntity.getId()));
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * @param account
     * @param state   0-未支付，1-已支付，2-已发货 3-待评论 4 已完成
     * @param start
     * @return
     */
    @Override
    public HashMap GetOrderData(String account, String state, int start) {
        HashMap<String, String> statemap = new HashMap<String, String>();
        statemap.put("0", "未支付");
        statemap.put("1", "已支付");
        statemap.put("2", "已发货");
        statemap.put("3", "待评论");
        statemap.put("4", "已完成");
        List<OrderEntity> orderEntities = backendOrderMapper.GetOrderData(account, state, start * 10);
        for (OrderEntity orderEntity : orderEntities) {
            orderEntity.setState(statemap.get(orderEntity.getState()));
            orderEntity.setRemark(getOrderRemark(orderEntity.getId()));
        }
        HashMap data = new HashMap();
        data.put("data", orderEntities);
        data.put("count", backendOrderMapper.GetOrderDataCount(account, state));


        return data;
    }

    /**
     * 根据提交状态和分单状态查询订单信息
     *
     * @param status
     * @param disStatus
     * @param account
     * @return
     */
    @Override
    public ArrayList<Order> QueryOrder(Integer start, String status, String disStatus, String account) {
        try {
            Info info = GetInfo(account);
            QueryOrder queryOrder = new QueryOrder(info.getUrl(), info.getAccount(), info.getPassword());

            return queryOrder.getData(start, status, disStatus);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据订单编号查询订单详情
     *
     * @param id
     * @param account
     * @return
     */
    @Override
    public ArrayList<OrderDetails> QueryOrderDetails(String id, String account) {
        try {
            Info info = GetInfo(account);
            QueryOrderDetails queryOrderDetails = new QueryOrderDetails(info.getUrl(), info.getAccount(), info.getPassword());
            return queryOrderDetails.getData(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public ArrayList<FOrder> QuerryYCRetailout(String state) {
        try {
            List<Acc> accList = backendOrderMapper.QuerryAcc();
            for (Acc acc : accList) {
                String account = acc.getAccount();
                // System.err.println(account);
                Info info = GetInfo(account);
                QuerySOrderRetailsCode querySOrderRetailsCode = new QuerySOrderRetailsCode
                        (info.getUrl(), info.getAccount(), info.getPassword());
                // List<String> retailCode = backendOrderMapper.QueryOrderRetailCode(state);//根据状态查询单号
                List<ShopOrder> shopOrders = backendOrderMapper.QueryOrderByState(state, account);
                for (ShopOrder shopOrder : shopOrders) {
                    //System.err.println(shopOrder.getRetailCode());
                    //查询云仓订单的分单状态
                    ArrayList<Order> data = querySOrderRetailsCode.getData(shopOrder.getRetailCode());

                    for (Order dat : data) {
                        //System.err.println(dat.getDisStatus());
                        //得到分单状态
                        String disStatus = dat.getDisStatus();

                        if (disStatus.equals("提交") && dat.getIsUp().equals("未同步")) {

                            QuerryYCRetailout querryYCRetailout = new QuerryYCRetailout
                                    (info.getUrl(), info.getAccount(), info.getPassword());

                            ArrayList<FOrder> forder = querryYCRetailout.getData(shopOrder.getRetailCode());
                            boolean kg = true;
                            UpdateYCFHIsUP updateYCFHIsUP = new UpdateYCFHIsUP(info.getUrl(), info.getAccount(), info.getPassword());

                            for (FOrder ford : forder) {
                                if (ford.getStaus().equals("提交") && ford.getIsUp().equals("未同步")) {
                                    String cEId = ford.getcExpresscompanyId();//快递公司
                                    String eN = ford.getExpresscompanyNo();//快递单号
                                    QueryMail queryMail = new QueryMail
                                            (info.getUrl(), info.getAccount(), info.getPassword());
                                    ArrayList<ShopMail> qm = queryMail.getData(cEId);
                                    for (ShopMail sp : qm) {
                                        String name = sp.getName();
                                        backendOrderMapper.InOrderMail(name, eN, shopOrder.getId());//将快递信息同步到
                                    }
                                    //同步发货单
                                    updateYCFHIsUP.getData(ford.getId(), "2");
                                    //队列发送模板消息
                                    String openid = backendOrderMapper.findOpenidByUid(shopOrder.getUid());
                                    if (null != openid) {
                                        queueService.putFinalPay(ford.getYcRetailId(),
                                                "已发货", ford.getCreationDate(),
                                                shopOrder.getAddress(), openid, account);
                                    }

                                } else {
                                    kg = false;
                                }
                            }
                            //所有发货单同步后修改订单状态
                            if (kg) {
                                /*修改云仓订单的同步状态*/
                                UpdateYCIsUP g = new UpdateYCIsUP(info.getUrl(), info.getAccount(), info.getPassword());
                                g.getData(dat.getId(), "2");
                                //提交状态修改订单状态=2
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
                                backendOrderMapper.UpOrderState(shopOrder.getId(), "2", sdf.format(new Date()));
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return null;
    }

    /**
     * 查询acc
     */
    @Override
    public List<Acc> QuerryAcc() {

        return backendOrderMapper.QuerryAcc();
    }


    private Info GetInfo(String token) {
        return accountMapper.GetAccData(token);
    }

    public static void main(String[] args) {


    }

}
